def f(x):
    return x ** 3 - 2 * x + 1


def df(x):
    return 3 * x ** 2 - 2


def newton_raphson(x0, epsilon, max_iter=1000):
    xn = x0
    for n in range(max_iter):
        fxn = f(xn)
        dfxn = df(xn)
        if abs(dfxn) < 1e-6:  # 避免除以零
            print("Warning: Derivative too small.")
            break
        xn_new = xn - fxn / dfxn
        if abs(xn_new - xn) < epsilon:
            print(f"Converged after {n + 1} iterations.")
            return xn_new
        xn = xn_new
    print("Max iterations reached without convergence.")
    return xn


# 选取不同的初始值
initial_values = [0.1, 0.5, 0.9]
epsilon = 0.01

for x0 in initial_values:
    min_x = newton_raphson(x0, epsilon)
    if min_x >= 1:
        min_x = 1
    if min_x <= 0:
        min_x = 0
    print(f"Initial value: {x0}, Approximate minimum x ≈ {min_x:.4f}")